﻿using Abp.Domain.Services;
using Abp.UI;
using shenghua.Authorization.Users;
using shenghua.SMS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Authorization.Verification
{
    /// <summary>
    /// 验证类
    /// </summary>
    public class VerificationManager: DomainService
    {
        private static readonly PhoneMapper _phoneMapper = new PhoneMapper();
        private readonly SMSManager _smsManager;
        private readonly UserManager _userManager;

        public VerificationManager(
            SMSManager smsManager,
            UserManager userManager
            )
        {
            _smsManager = smsManager;
            _userManager = userManager;
        }

        /// <summary>
        /// 验证是否是已经经过验证的手机号
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public async Task<bool> CheckPhoneNumber(string phoneNumber)
        {
            var user = await _userManager.FindByPhoneNumberAsync(phoneNumber);
            return user != null;
        }

        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public async Task SendPhoneCaptcha(string phoneNumber)
        {
            // 生成验证码
            string captcha = SMSManager.GenerateCaptcha();
            // 给手机发短信
            _smsManager.SendCaptcha(phoneNumber, captcha);
            // 记录验证码
            _phoneMapper.Add(phoneNumber, captcha);
        }

        /// <summary>
        /// 验证手机验证码
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="captcha"></param>
        /// <returns></returns>
        public async Task<bool> CheckPhoneCaptcha(string phoneNumber, string captcha)
        {
            return _phoneMapper.CheckCaptcha(phoneNumber, captcha);
        }

        /// <summary>
        /// 通过手机重置密码
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="captcha"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public async Task ResetPasswordByPhone(string phoneNumber, string captcha, string newPassword)
        {
            if(!_phoneMapper.CheckCaptcha(phoneNumber, captcha))
            {
                throw new UserFriendlyException("未验证的手机号或无效的验证码");
            }

            var user = await _userManager.FindByPhoneNumberAsync(phoneNumber);
            string token = await _userManager.GeneratePasswordResetTokenAsync(user);
            var result = await _userManager.ResetPasswordAsync(user, token, newPassword);

            if (!result.Succeeded)
            {
                throw new UserFriendlyException(result.Errors.First().Description);
            }
        }
    }
}
